package qeug.shsh.bpm.utils;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityType;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.workflow.WorkflowServiceHelper;
import kd.bos.workflow.api.BizProcessStatus;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @projectName: qeug-cosmic-root-project
 * @package: qeug.shsh.bpm.service.impl
 * @className: BPMServiceImpl
 * @author: wenyx
 * @modifier: xuhh
 * @description: TODO
 * @date: 2023/11/3/16:21
 * @version: 2.0
 */
public class BPMUtil {

    private static HashMap<String, String> billTpeMap = new HashMap<>();

    static {
        billTpeMap.put("CCS接待申请", "er_dailyapplybill");
        billTpeMap.put("CCS车辆维修保养申请", "er_dailyapplybill");
        billTpeMap.put("CCS租房补贴申请", "er_dailyapplybill");
        billTpeMap.put("CCS误餐补贴申请", "er_dailyapplybill");
        billTpeMap.put("CCS探亲申请", "er_dailyapplybill");
        billTpeMap.put("CCS费用申请", "er_dailyapplybill");
        billTpeMap.put("CCS费用报销", "er_dailyreimbursebill");
        billTpeMap.put("CCS出差申请", "er_tripreqbill");
        billTpeMap.put("CCS差旅报销", "er_tripreimbursebill");
        billTpeMap.put("CCS借款", "er_dailyloanbill");
        billTpeMap.put("CCS还款", "er_repaymentbill");
        billTpeMap.put("CCS资金计划", "qeug_fundplan");
        billTpeMap.put("CCS资金计划调整", "qeug_fundadjust");
        billTpeMap.put("CCS预算表", "eb_reportbyscheme");
        billTpeMap.put("CCS预算调整", "bgm_adjustbill");
        billTpeMap.put("CCS预算调剂", "bgm_adjpstbill");
    }

    /**
     * @param strProcessName 流程名称
     * @return 单据标识
     */
    public static String getbillentity(String strProcessName) {
        return billTpeMap.get(strProcessName);
    }

    /**
     * @param billentity 实体名
     * @return 流程名
     */
    public static String getProcessName(String billentity) {
        return getKeyByValue(billTpeMap, billentity);
    }

    /**
     * @param billinfo 单据数据
     * @param type     分辩单据类型
     * @return billno 单据编号 ，companyName 公司名称 ，billType 单据类型 ，username 管理员名字 ，adminName 部门名称
     * 使用单据：差旅报销单，费用报销单，预算调整单
     */
    public static String getSummary(DynamicObject billinfo, int type) {
        // 获取账单号
        String billno = billinfo.getString("billno");

        String billType = "";//单据类型
        String adminName = "";//部门
        String companyName = "";//公司
        String accountName = "";//员工供应商开户名称

        // 获取单据类型
//        if (type == 1) {
//            DynamicObject billtype_data = billinfo.getDynamicObject("qeug_document_type");
//            billType = billtype_data.getString("name");
//        } else if (type == 2) {
//            DynamicObject billtype_data = billinfo.getDynamicObject("triptype");
//            billType = billtype_data.getString("name");
//        } else if (type == 3) {
//            DynamicObject billtype_data = billinfo.getDynamicObject("qeug_billtypefield");
//            billType = billtype_data.getString("name");
//        } else if (type == 4) {
//            DynamicObject billtype_data = billinfo.getDynamicObject("qeug_billtype");
//            billType = billtype_data.getString("name");
//        }
        // 获取申请人信息
//        DynamicObject applier = billinfo.getDynamicObject("applier");
        // 获取管理员信息
//        String username = applier.getString("name");
        IDataEntityType dataEntityType = billinfo.getDataEntityType();
        String dataEntityTypeName = dataEntityType.getName();//单据标识
        if ("bgm_adjustbill".equals(dataEntityTypeName)) {
            //预算调整单
            String adjustreason = billinfo.getString("adjustreason").substring(0, Math.min(20, billinfo.getString("adjustreason").length()));//调整原因
            DynamicObject admin = billinfo.getDynamicObject("qeug_costdept");//一级承担部门
            adminName = admin.getString("name");
            return "预算调整申请" + billno  + adminName + adjustreason;
            //                     单号       一级部门    调整原因（前20个字符）
        } else {
            DynamicObject company = billinfo.getDynamicObject("costcompany");//费用承担公司
            companyName = company.getString("name");
            DynamicObject costDept = billinfo.getDynamicObject("qeug_costdept");//一级承担部门
            adminName = costDept.getString("name");
            DynamicObjectCollection accountEntryCollection = billinfo.getDynamicObjectCollection("accountentry");//收款信息
            DynamicObject accountEntry = accountEntryCollection.get(0);
            accountName = accountEntry.getString("payeraccountname");//账户名称
            BigDecimal oriReceiveAmount = accountEntry.getBigDecimal("orireceiveamount").setScale(2, RoundingMode.HALF_UP); // 收款金额，保留两位小数
            return billno + companyName + accountName + adminName + oriReceiveAmount;
            //     单号     费用承担公司   员工供应商开户名称  费用承担一级部门   总金额
        }
    }

    /**
     * @param billInfo 单据数据
     * @return 单号(billNo)+付款公司（收款的）（costcompany）+收款金额（orireceiveamount）+ 申请人（applier） +申请部门（org）
     * 供应商名称（billPayerIdName）+金额（bigDecimal）+业务员（salesmanName）+部门（costDeptName）+备注的前20个字（description）
     */
    public static String getSummaryV2(DynamicObject billInfo) {
        String billNo = billInfo.getString("billno");//单号
        IDataEntityType dataEntityType = billInfo.getDataEntityType();
        String dataEntityTypeName = dataEntityType.getName();//单据标识
        if ("er_publicreimbursebill".equals(dataEntityTypeName) || "er_dailyloanbill".equals(dataEntityTypeName)) {
            //付款申请单,借款单
            DynamicObject costCompany = billInfo.getDynamicObject("costcompany");//费用承担公司
            String costCompanyName = null;
            if (costCompany != null) {
                costCompanyName = costCompany.getString("name");//费用承担公司名称
            }
            DynamicObjectCollection accountEntry = billInfo.getDynamicObjectCollection("accountentry");//收款信息分录
            DynamicObject dynamicObject = accountEntry.get(0);
            BigDecimal oriReceiveAmount = dynamicObject.getBigDecimal("orireceiveamount").setScale(2, RoundingMode.HALF_UP); // 收款金额，保留两位小数
            DynamicObject applier = billInfo.getDynamicObject("applier");//申请人
            String applierName = null;
            if (applier != null) {
                applierName = applier.getString("name");//申请人名称
            }
            DynamicObject costDept = billInfo.getDynamicObject("qeug_costdept");//一级承担部门
            String costDeptName = null;
            if (costDept != null) {
                costDeptName = costDept.getString("name");//申请部门名称
            }
            return billNo + costCompanyName + oriReceiveAmount + applierName + costDeptName;
        } else {
            //资金计划，资金计划调整
            DynamicObject costCompany = billInfo.getDynamicObject("org");//公司
            String costCompanyName = null;
            if (costCompany != null) {
                costCompanyName = costCompany.getString("name");//公司
            }
            DynamicObject applier = billInfo.getDynamicObject("qeug_sqperson");//申请人
            String applierName = null;
            if (applier != null) {
                applierName = applier.getString("name");//申请人名称
            }
            DynamicObject org = billInfo.getDynamicObject("qeug_costdept");//一级承担部门
            String orgName = null;
            if (org != null) {
                orgName = org.getString("name");//部门名称
            }
            return billNo + costCompanyName + applierName + orgName;
        }
//        String description = null /*billInfo.getString("description").substring(0, Math.min(20, billInfo.getString("description").length()))*/;//事由
//        return billNo + billPayerIdName + bigDecimal + salesmanName + costDeptName + description;
    }


    public static <K, V> K getKeyByValue(Map<K, V> map, V value) {
        for (Map.Entry<K, V> entry : map.entrySet()) {
            if (value.equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }

    /**
     * 工作流完成任务
     *
     * @param billNo 单据编号
     * @param state  同意状态
     */
    public static void actionWorkFlow(String billNo, String state, String entityNum) {
        QFilter[] q = new QFilter[]{new QFilter("billno", "=", billNo)};
        DynamicObject bill = BusinessDataServiceHelper.loadSingle(entityNum, q);
        QFilter[] qFilters = new QFilter[]{new QFilter("number", "=", "BPM")};//默认BPM
        DynamicObject user = BusinessDataServiceHelper.loadSingle("bos_user", qFilters);
        String billId = bill.getString("id");
        Long taskID = WorkflowServiceHelper.getTaskIdByBusinessKeyAndUserId(billId, user.getLong("id"));
        long id = user.getLong("id");
        String opNumber = "";
        if (state.equals("同意")) {
            opNumber = "Consent";
        } else if (state.equals("驳回")) {
            opNumber = "Reject";
        } else if (state.equals("终止")) {
            opNumber = "stop";
        }
        WorkflowServiceHelper.completeTask(taskID, id, opNumber, "无");
    }
}

